<?php
namespace plugin\ai\app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AccessControl implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        // 如果是options请求则返回一个空响应，否则继续向洋葱芯穿越，并得到一个响应
        if ($request->method() == 'OPTIONS') {
            $response = response('');
        } else {
            if (config('plugin.ai.app.need_login') && !session('user')) {
                if ($request->expectsJson()) {
                    $response = json(['code' => -1, 'msg' => '请登录', 'error' => ['message' => '请[登录](/app/user/login?redirect=/app/ai)']]);
                } else {
                    $response = redirect('/app/user/login');
                }
            } else {
                $response = $handler($request);
            }
        }
        //$response = $handler($request);
        // 给响应添加跨域相关的http头
        $response->withHeaders([
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
        ]);

        return $response;
    }
}